﻿function request(url, params, success, failure) {
    window.Ext.Ajax.request({
        url: url,
        params: params,
        method: 'POST',
        success: success,
        failure: failure
    });
}

function showNotification(obj, result, callback) {
    result = window.Ext.decode(result.responseText);
    showNotificationFromJson(obj, result, callback);
}

function formatMessage(s) {
    var data = window.Ext.decode(s, true);
    if (data)
        if (data.length > 0) {
            var first = '';
            var result = '';
            for (var i = 0; i < data.length; i++) {
                result += first + data[i];
                if (first == '')
                    first = '<br/>';
            }
            return result;
        }
    return '';
}

function showNotificationFromJson(obj, result, callback) {
    $('.validation-summary-errors').html('');
    if (result)
        if (result.lv == 1) {
            obj.Ext.net.Notification.show({
                iconCls: 'icon-information',
                html: formatMessage(result.msg),
                title: 'Notification'
            });
            if (callback)
                callback();
        } else {
            if (result.msg)
                if (result.msg.length > 0) {
                    if ($('.validation-summary-errors').length == 0)
                        window.Ext.Msg.show({
                            title: "Confirm",
                            buttons: window.Ext.Msg.YES,
                            icon: window.Ext.Msg.ERROR,
                            msg: formatMessage(result.msg)
                        });
                    else {
                        var msg = window.Ext.decode(result.msg);
                        for (var i = 0; i < msg.length; i++)
                            addModelError(msg[i]);
                    }
                }
            if (result.forms) {
                var forms = window.Ext.decode(result.forms);
                if (forms)
                    for (var k in forms) {
                        if (window.App)
                            if (window.App[k])
                                window.App[k].markInvalid(forms[k]);
                        addModelError(forms[k]);
                    }
            }
        }
    else
        obj.Ext.net.Notification.show({
            iconCls: 'icon-information',
            html: 'Error when updated.',
            title: 'Notification'
        });
}

function addModelError(err) {
    var tmp = $('.validation-summary-errors ul');
    if (tmp.length == 0) {
        $('.validation-summary-errors').append('<ul></ul>');
        tmp = $('.validation-summary-errors ul');
    }
    tmp.append('<li>' + err + '</li>');
}